package com.caltco.cargo.ops.common.utils;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class MyAckReceiver implements ChannelAwareMessageListener {

    public List<Map<String,String>> userList = new ArrayList<>();

    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            // 因为传递消息的时候用的map传递,所以将Map从Message内取出需要做些处理
            String msg = message.toString();
            // 可以点进Message里面看源码,单引号直接的数据就是我们的map消息数据
            String[] msgArray = msg.split("'");
            Map<String, String> msgMap = mapStringToMap(msgArray[1].trim(),3);

            // 当退出登录的时候，完成在线用户列表的登录状态的修改
            if (msgMap.get("state").equals("0")){
                for (Map<String,String> item : userList){
                    if (item.get("userId").equals(msgMap.get("userId"))){
                        item.put("state","0");
                        break;
                    }
                }
            } else {
                if (userList.size() > 0) {
                    for (Map<String, String> item : userList) {
                        if (item.get("userId").equals(msgMap.get("userId"))) {
                            userList.remove(item);
                            break;
                        }
                    }
                }
                if (!msgMap.isEmpty()){
                    userList.add(msgMap);
                }
            }
//            userList = userList.stream().distinct().collect(Collectors.toList());
            String userId=msgMap.get("userId");
            String realName=msgMap.get("realName");
            String state=msgMap.get("state");
            System.out.println("  MyAckReceiver  userId:"+userId+"  realName:"+realName+"   state:"+state);
            System.out.println("消费的主题消息来自："+message.getMessageProperties().getConsumerQueue());
            //第二个参数，手动确认可以被批处理，当该参数为 true 时，则可以一次性确认 delivery_tag 小于等于传入值的所有消息
            // channel.basicRecover(true);
			// channel.basicReject(deliveryTag, true);//第二个参数，true会重新放回队列，所以需要自己根据业务逻辑判断什么时候使用拒绝
        } catch (Exception e) {
            channel.basicReject(deliveryTag, false);
            e.printStackTrace();
        } finally {
             channel.basicAck(deliveryTag, true);
        }
    }

    //{key=value,key=value,key=value} 格式转换成map
    private Map<String, String> mapStringToMap(String str,int entryNum ) {
        str = str.substring(1, str.length() - 1);
        str= str.replace("\"", "");
        String[] strs = str.split(",",entryNum);
        Map<String, String> map = new HashMap<String, String>();
        for (String string : strs) {
            String key = string.split(":")[0].trim();
            String value = string.split(":")[1];
            map.put(key, value);
        }
        return map;
    }

    public List<Map<String, String>> getUserList() {
        return userList;
    }

    public void setUserList(List<Map<String, String>> userList) {
        this.userList = userList;
    }

}